var http = require("http"),
    JSONUtil = require("./json-util"),
    url = require("url"),
    qs = require("querystring");


var HttpUtil = {
    POST: function (_url, params, cb) {
        _url = url.parse(_url, true);
        var opt = {
            method: "POST",
            host: _url.hostname,
            port: _url.port,
            path: _url.path,
            keepAlive: true,
            headers: {
                "Content-Type": 'application/x-www-form-urlencoded',
                "Accept": "application/json"
            }
        };
        var req = http.request(opt, function (res) {
            if (res.statusCode == 200) {
                var jsonUtil = new JSONUtil();
                jsonUtil.parseResponse(res, function (error, data) {
                    cb(error, data);
                });
            } else {
                var error = "call remote method error";
                cb(error)
            }
        });
        if (params) {
            req.write(qs.stringify(params));
        }
        req.end();
    },
    GET: function (_url, params, cb) {
        if (params) {
            if (_url.indexOf("?") > -1) {
                _url += "&";
            } else {
                _url += "?";
            }
            _url += qs.stringify(params);
        }
        http.get(_url, function (res) {
            if (res.statusCode == 200) {
                var jsonUtil = new JSONUtil();
                jsonUtil.parseResponse(res, function (error, data) {
                    cb(error, data);
                });
            } else {
                var error = "call remote method error";
                cb(error)
            }
        });
    }
};

module.exports = HttpUtil;